<?php

  require_once('functions.php');
  session_start();
  date_default_timezone_set('Asia/Kolkata');
  /******* DB CONNECT START  ***********/
  $host = 'localhost';
  $username = 'root';
  $password = '';
  $dbName = 'nb158h';
  mysql_connect($host, $username, $password) or die('CONNECTION REFUSED ------'.mysql_error());
  mysql_select_db($dbName) or die('DB SELECTION FAILED ------'.mysql_error());
  /******* DB CONNECT ENDS  ***********/


  function insert($tableName='', $data )
  {
    if($tableName =='' || empty($data)){return 0;}

    $query = "INSERT INTO $tableName SET ";
    foreach($data as $colName=>$colValue) {
      $query .= " `$colName`='$colValue' ,";
    }
    $query = rtrim($query, ' ,');
    pr($query,__LINE__,__FILE__);
    mysql_query($query) or die(mysql_error());
    return mysql_insert_id();
  }

  function updateById($tableName='', $data, $uid )
  {
    if($tableName ==''
    || empty($data)
    || $uid == 0){
      return 0;
    }

    $query = "UPDATE $tableName SET ";
    foreach($data as $colName=>$colValue) {
      $query .= " `$colName`='$colValue' ,";
    }
    $query = rtrim($query, ' ,');
    $query .= " WHERE `id`=$uid";
    //echo $query;
    pr($query,__LINE__,__FILE__);
    mysql_query($query) or die(mysql_error());
    return mysql_affected_rows();
  }

  /*
   * $tableName="`users`"
   * $where="`name` lIKE '%ravi%'"
   * $colName="`id`,`uname`,`dob`,`password`"
   * $order="`uname` ASC"
   * $limit="LIMIT 10,5" {From id 11 to 15}
   *
   */
  function fetchAll($tableName='',$where='',$colName='',$order='',$limit='')
  {
    if($tableName ==''){
      return 0;
    }

    if($where !=''){
      $where = "WHERE $where";
    }

    $query = "SELECT * FROM `$tableName` $where $limit";
    pq($query,__LINE__,__FILE__);
    $result = mysql_query($query) or die(mysql_error());
    return $result;
  }

  function fetchById($tableName='',$id=0)
  {
    if($tableName ==''){
      return 0;
    }

    $query = "SELECT * FROM `$tableName` WHERE `id`='$id'";
    pq($query,__LINE__,__FILE__);
    $result = mysql_query($query) or die(mysql_error());
    $ans = mysql_fetch_assoc($result);
    return $ans;
  }

  function countAll($tableName='')
  {
    if($tableName ==''){
      return 0;
    }

    $query = "SELECT COUNT(*)as `total` FROM `$tableName`";
    pq($query,__LINE__,__FILE__);
    $result = mysql_query($query) or die(mysql_error());
    $ans = mysql_fetch_assoc($result);
    //pr($ans);
    return $ans['total'];
  }




